<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <title>学习空间</title>
    <style>
        body {
          margin: 0;
          font-family: Arial, sans-serif;
          background: #f6f8fa;
        }
        .navbar {
          background-color: #2c3e50;
          color: white;
          padding: 10px 20px;
          display: flex;
          justify-content: space-between;
          align-items: center;
        }
        .logo {
          font-size: 20px;
          font-weight: bold;
        }
        .user-actions button {
          margin-left: 10px;
          padding: 6px 12px;
          cursor: pointer;
        }
        .main {
          max-width: 600px;
          margin: 40px auto;
        }

        .post-box {
          background: white;
          padding: 20px;
          border-radius: 8px;
          box-shadow: 0 0 6px rgba(0,0,0,0.1);
          margin-bottom: 20px;
        }
        .post-box textarea {
          width: 100%;
          padding: 10px;
          font-size: 14px;
          resize: none;
          border-radius: 4px;
          border: 1px solid #ccc;
        }
        .post-box button {
          margin-top: 10px;
          float: right;
          padding: 6px 14px;
          background: #3498db;
          border: none;
          color: white;
          border-radius: 4px;
          cursor: pointer;
        }

        .post-list {
          background: white;
          padding: 20px;
          border-radius: 8px;
          box-shadow: 0 0 6px rgba(0,0,0,0.1);
        }
        .post-item {
          padding: 10px 0;
          border-bottom: 1px solid #eee;
        }
        .post-item:last-child {
          border-bottom: none;
        }

        .modal {
          display: none;
          position: fixed;
          top: 0; left: 0;
          width: 100%; height: 100%;
          background-color: rgba(0,0,0,0.5);
          justify-content: center;
          align-items: center;
        }
        .modal-content {
          background-color: white;
          padding: 20px;
          border-radius: 6px;
          width: 300px;
        }
        .modal-content input {
          width: 100%;
          margin: 5px 0;
          padding: 8px;
        }
    </style>
</head>
<body>

<!-- 顶部用户栏 -->
<div class="navbar">
    <div class="logo">学习空间 LOGO</div>
    <div class="user-actions" id="user-actions"></div>
</div>

<!-- 主体内容 -->
<div class="main">
    <!-- 发帖输入框 -->
    <div class="post-box">
        <textarea id="postInput" placeholder="问点什么..." rows="3"></textarea>
        <button onclick="submitPost()">发布</button>
    </div>

    <!-- 静态帖子列表 -->
    <div class="post-list" id="postList">
        <h3>最新动态</h3>
        <div class="post-item">👋 欢迎加入学习空间！</div>
        <div class="post-item">📢 新版课程将在 9 月上线，敬请期待！</div>
        <div class="post-item">🎯 “每日打卡”小程序上线啦～</div>
    </div>
</div>

<!-- 登录弹窗 -->
<div class="modal" id="loginModal">
    <div class="modal-content">
        <h3>用户登录</h3>
        <input type="text" id="loginUsername" placeholder="用户名">
        <input type="password" id="loginPassword" placeholder="密码">
        <button onclick="submitLogin()">登录</button>
        <button onclick="closeLogin()">取消</button>
    </div>
</div>

<script>
    const tokenKey = "jwt_token";

    // 用户栏渲染逻辑（传入用户名）
    function renderUserBar(username = null) {
      const actions = document.getElementById("user-actions");
      actions.innerHTML = "";

      if (username) {
        actions.innerHTML = `
          <span>${username}</span>
          <button onclick="logout()">退出</button>
        `;
      } else {
        actions.innerHTML = `
          <button onclick="openLogin()">登录</button>
          <a href="/register.html"><button>注册</button></a>
        `;
      }
    }

    // 从服务器检查token是否有效并获取用户名
    function checkLoginStatusFromServer() {
      const token = localStorage.getItem(tokenKey);
      if (!token) {
        renderUserBar(null);
        return;
      }

      fetch("/api/auth/status", {
        method: "GET",
        headers: {
          "Authorization": "Bearer " + token
        }
      })
      .then(res => {
        if (!res.ok) throw new Error("无效或过期的 token");
        return res.json();
      })
      .then(data => {
        renderUserBar(data.username);
      })
      .catch(err => {
        console.warn("登录状态失效：", err.message);
        localStorage.removeItem(tokenKey);
        renderUserBar(null);
      });
    }

    function openLogin() {
      document.getElementById("loginModal").style.display = "flex";
    }

    function closeLogin() {
      document.getElementById("loginModal").style.display = "none";
    }

    function submitLogin() {
      const username = document.getElementById("loginUsername").value;
      const password = document.getElementById("loginPassword").value;

      fetch("/api/auth/login", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ username, password })
      })
      .then(res => {
        if (!res.ok) throw new Error("登录失败");
        return res.json();
      })
      .then(data => {
        localStorage.setItem(tokenKey, data.token);
        closeLogin();
        checkLoginStatusFromServer();
      })
      .catch(err => alert("登录失败：" + err.message));
    }

    function logout() {
      const token = localStorage.getItem(tokenKey);
      fetch("/api/auth/logout", {
        method: "POST",
        headers: {
          "Authorization": "Bearer " + token
        }
      }).finally(() => {
        localStorage.removeItem(tokenKey);
        renderUserBar(null);
      });
    }

    function submitPost() {
      const content = document.getElementById("postInput").value.trim();
      if (!content) return alert("内容不能为空");

      const postList = document.getElementById("postList");
      const newItem = document.createElement("div");
      newItem.className = "post-item";
      newItem.textContent = content;

      postList.insertBefore(newItem, postList.children[1]);
      document.getElementById("postInput").value = "";
    }

    window.onload = checkLoginStatusFromServer;
</script>

</body>
</html>
